#ifndef _COMM_HPP_
#define _COMM_HPP_
#include <iostream>
#include <string>
#include <sys/types.h>

#include <sys/ipc.h>
#include <sys/shm.h>
#include <cstring>
#include "log.hpp"
using namespace std;
Log log;
const int size = 4096;
// const string pathname = "/home/yzx";
// const int proj_id = 0x6666;
const string pathname = "/home/yzx";
const int proj_id = 0x6666;
#define FIFO_FILE "./myfifo"
#define MODE 0664
key_t GetKey()
{
    key_t k = ftok(pathname.c_str(), proj_id);
    if (k < 0)
    {
        log(Fatel, "ftok error,error string:%s", strerror(errno));
        exit(1);
    }
    log(Info, "ftok success key:%d", k);

    return k;
}
int GetshareMemHelper(int flags)
{
    key_t k = GetKey();
    int shmid = shmget(k, 4096, flags);
    if (shmid < 0)
    {
        log(Fatel, "shmget error ,error string:%s", strerror(errno));
        exit(2);
    }
    log(Info, "ftok success shmid:%d", shmid);
    return shmid;
}
int CreatShm()
{
    return GetshareMemHelper(IPC_CREAT | IPC_EXCL | 0666);
}
int GetShm()
{
    return GetshareMemHelper(IPC_CREAT);
}

enum
{
    FIFO_CREAT_ERR = 1,
    FIFO_DELETE_ERR,
    FIFO_OPEN_ERR
};

class Init
{
public:
    Init()
    {
        int n = mkfifo(FIFO_FILE, 0666);
        if (n == -1)
        {
            // printf("%d:%s\n", errno, strerror(errno));
            perror("mkfifo");
            exit(FIFO_CREAT_ERR);
        }
    }
    ~Init()
    {
        int m = unlink(FIFO_FILE);
        if (m == -1)
        {
            perror("unlink");
            exit(FIFO_DELETE_ERR);
        }
    }
};
#endif